home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: tank.news.pipex.net!pipex!warwick!bsmail!talisker!nathan
- From: nathan@pact.srf.ac.uk (Nathan Sidwell)
- Subject: Re: How do I round and truncate floats to integers?
- Message-ID: <Dn2L2u.GqG@uns.bris.ac.uk>
- Sender: usenet@uns.bris.ac.uk (Usenet news owner)
- Nntp-Posting-Host: talisker.pact.srf.ac.uk
- Organization: Inmos
- X-Newsreader: TIN [version 1.2 PL2]
- References: <4g009b$c2n@news.tuwien.ac.at> <4gbb0p$c7s@news1.radix.net>
- Date: Tue, 20 Feb 1996 10:28:05 GMT
-
- Jim Ward (jfw@radix.net) wrote:
- : In article <4g009b$c2n@news.tuwien.ac.at>, sor@rs6.iaee.tuwien.ac.at says...
- : >Given a float (double, to be exact) how do I
- : >
- : >1) round it to nearest integer (forget 0.5 problem for the moment) and
-
- : A technique that also works for both positive and negative numbers is:
-
- : (int) x < 0.0 ? ceil(x - 0.5) : floor(x + 0.5);
-
- : I got this from p.135 of Plauger's The Standard C Library.
- Why would one want to round halves away from zero? This is a most bizarre
- rounding.
-
- If one wants consistent rounding of halves towards plus infinity, then
- floor(x + 0.5) will suffice. to round halves to minus infinity then
- ceil(x - 0.5) will suffice.
-
- The conversion (int)x, will convert x to an integer by 'discarding the
- fractional part' (3.2.1.3). Will this round towards zero?
- The standard does not define the format of floating point numbers,
- in particular it does not proscribe 2's complement floating point number
- formats. Discarding the fractional part of a twos complement
- representation is equivalent to rounding to minus infinity.
- I must conclude that it is implementation defined as to whether
- conversion of a negative floating point value to an integer returns
- the integer closer to zero, or the one closer to minus infinity.
- (The standard does not explicitly mention this though.)
-
- nathan
-
- --
- Nathan Sidwell Holder of the Xmris home page
- Chameleon Architecture Group at SGS-Thomson, formerly Inmos
- http://www.pact.srf.ac.uk/~nathan/ Tel 0117 9707182
- nathan@inmos.co.uk or nathan@bristol.st.com or nathan@pact.srf.ac.uk
-